import json
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import render

from learning_logs.models import Topic


def index(request):
    return render(request, 'index.html')


@login_required
def topics(request):
    return render(request, 'topics.html')


@login_required
def add_topic(request):
    name = request.POST.get("name")

    try:
        Topic.objects.get(name=name, owner=request.user)
    except Topic.DoesNotExist:
        topic = Topic.objects.create(name=name, owner=request.user)
        return JsonResponse({
            'code': 0,
            'msg': 'success',
            'topic': {
                'id': topic.id,
                'name': topic.name,
                'datetime': datetime.strftime(topic.datetime, '%Y-%m-%d %H:%M:%S'),
                'owner': request.user.username
            }
        })

    return JsonResponse({'code': 1, 'msg': 'failed'})


@login_required
def del_topic(request):
    body = json.loads(request.body)
    print(body)
    Topic.objects.filter(id=body.get('id')).delete()
    return JsonResponse({'code': 0, 'msg': 'success'})


@login_required
def mod_topic(request):
    modify = json.loads(request.body)
    Topic.objects.filter(id=modify.get('id')).update(name=modify.get('name'))
    return JsonResponse({'code': 0, 'msg': 'success'})


@login_required
def list_topic(request):
    topic_info = []
    keywords = request.GET.get('keywords')
    if keywords == "":
        query_set = Topic.objects.filter(owner=request.user)
    else:
        query_set = Topic.objects.filter(owner=request.user, name__contains=keywords)
    query_set = list(query_set.order_by('-datetime').values())
    for query in query_set:
        query["datetime"] = datetime.strftime(query["datetime"], '%Y-%m-%d %H:%M:%S')
        query["owner"] = User.objects.get(id=query.pop("owner_id")).username
        topic_info.append(query)
    return JsonResponse({'topics': topic_info})
